package com.dao;

import java.util.List;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class DBUtil {

	private static Mongo mg = null;
	private static Morphia morphia;
	private static Datastore ds;
	
    private static String dbName="MyDeal";
    
    private static String dburl="127.0.0.1";
    private static String username="sa";
    private static String password="sa";
    
    public static Datastore getDatastore() {
		if (mg == null) {
			try {
				mg = new Mongo(dburl,27017);
		        morphia = new Morphia();
		        morphia.map(DealBean.class);
		        ds = morphia.createDatastore(mg, dbName, username,
		        		password.toCharArray());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

        return ds;
	}
    
    public static void save(Object obj)
    {
    	Datastore ds=getDatastore();
    	ds.save(obj);
    }
    
    public static void del(Object obj)
    {
    	Datastore ds=getDatastore();
    	ds.delete(obj);
    }
    
    public static List findBy(Object obj,String field,String value)
    {
    	//List  list = ds.find(obj.getClass(), "stars >=", 4).asList();
    	Datastore ds=getDatastore();
    	List  list = ds.find(obj.getClass(), field, value).asList();
    	return list;
    }
    
    public static List findAll(Object obj)
    {
    	Datastore ds=getDatastore();
    	List ls=ds.find(obj.getClass()).asList();
    	return ls;
    }

}
